package com.situ.student.common;

import com.situ.student.model.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public static final String LOGIN_USER_KEY = "@#login_user";
    private static final String[] WHITE = {"/admin/login/**", "/assets/**", "/admin/captcha/**", "/admin/logout/**"};

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        uri = uri.replace(req.getContextPath(), "");

        //路径匹配器
        PathMatcher matcher = new AntPathMatcher();
        for (String pattern : WHITE) {
            if (matcher.match(pattern, uri)) {
                chain.doFilter(request, response);
                return;
            }
        }

        //会话域
        HttpSession session = req.getSession();
        System.out.println(session.getId());

        //全局域
        ServletContext ctx = req.getServletContext();


        User user = (User) session.getAttribute(LOGIN_USER_KEY);
        if (user == null) {//未登录
            resp.sendRedirect(req.getContextPath() + "/admin/login");
        } else {
            chain.doFilter(request, response);
        }
    }
}
